package LinkedDemo;
/**
@Auther: MFM
@Date: 2021/7/30 - 07 - 30 - 16:45 
@version: 1.0
*/

public class LinkedDemo {
    public static class Node<T>{
        //当前节点的下一个节点是哪一个
        public Node<T> next;

        //链表的第一个节点，以及最后一个节点，当前节点
        private Node<T> first;
        private Node<T> last;

        //当前链表的长度
        private int size = 0;

        //链表当前的这个节点上存储的数据
        private T value;

        public T getValue(){
            return this.value;
        }
        private void setValue(T value){
            this.value=value;
        }

        public int size() {
            return this.size;
        }
        //为链表提供一个add方法
        public void add(T value){
            Node node = new Node();
            node.setValue(value);
            if (first == null){//第一次添加
                first = node;
                last = node;
            }else {
                last.next = node;
                last=node;
            }
            this.size++;
        }

        public T remove(T value){
            Node<T> previous = null;
            Node<T> current = this.first;
            while (current.next!=null){
                if (current.value.equals(value)){
                    if (current==this.first){
                        this.first = current.next;
                    }else {
                        previous.next = current.next;
                    }
                    this.size--;
                    return current.getValue();
                }

                previous = current;
            }
            return null;
        }

        @Override
        public String toString() {
            StringBuilder builder = new StringBuilder();
            Node<T> current = this.first;
            builder.append("[");
            while (current!=null) {
                builder.append(current.value).append(",");
                current = current.next;
            }
            builder.deleteCharAt(builder.length()-1);
            builder.append("]");
            return builder.toString();
        }

        public static void main(String[] args) {
            Node<Integer> node = new Node<>();
            node.add(1);
            node.add(3);
            System.out.println(node.size);
            System.out.println(node);
        }
    }
}
